package com.lj.common_web.filter;

import com.lj.common_web.response.ResponseCode;
import com.lj.common_web.response.ResponseVO;
import com.lj.common_web.utils.RepeatedlyHttpServletRequestWrapper;
import com.lj.common_web.utils.ServletUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author luojing
 * @since 2025/5/27 18:31
 */
public class SignFilter extends OncePerRequestFilter {

    private final VerifySignature verifySignature;

    public SignFilter(VerifySignature verifySignature) {
        this.verifySignature = verifySignature;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        request = new RepeatedlyHttpServletRequestWrapper(request);
        try {
            verifySignature.verify(request, response);
        } catch (Exception e) {
            ServletUtil.writeJson(response, ResponseVO.error(ResponseCode.BAD_REQUEST, e.getMessage()));
            return;
        }
        filterChain.doFilter(request, response);
    }
}
